package com.sh.data.engine.application.service.login;

import com.alibaba.fastjson2.JSONObject;
import com.aliyun.gts.sso.boot.SFSSOLoginProperties;
import com.aliyun.gts.sso.domain.CookieDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author: mengzheng.mhc
 * @date: 2024/8/8 16:51
 */
@Slf4j
@Service
public class LoginApplicationService {

    @Autowired
    private SFSSOLoginProperties sfSSOLoginProperties;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String host = request.getHeader("Host");
        if (StringUtils.isBlank(host)) {
            host = this.sfSSOLoginProperties.getHost();
        }
        CookieDTO cookieDTO = new CookieDTO();
        cookieDTO.setName(this.cookieName());
        cookieDTO.setValue("");
        cookieDTO.setDomain(host);
        cookieDTO.setMaxAge(0);
        cookieDTO.setHttpOnly(true);
        cookieDTO.setPath(contextPath);
        if ("https".equalsIgnoreCase(this.sfSSOLoginProperties.getSchema())) {
            cookieDTO.setSecure(true);
        }

        response.addHeader("Set-Cookie", this.cookieName() + "=" + cookieDTO.getValue() + "; Path=" + contextPath);

        JSONObject json = new JSONObject();
        json.put("data", true);
        json.put("status", 200);
        json.put("code", 200);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json.toJSONString());
    }

    private String cookieName() {
        return "SF_SSO_" + this.sfSSOLoginProperties.getHost();
    }
}
